package com.example.harmonyos_orm.app;

import com.zhushenwudi.hmutils.net.PendingLiveData;
import com.zhushenwudi.hmutils.ormdao.DataHelper;
import com.zhushenwudi.hmutils.scheduler.HmOSSchedulers;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.Lifecycle;
import ohos.data.preferences.Preferences;

import java.util.concurrent.TimeUnit;

/**
 * slice基类
 */
public class BaseAbilitySlice extends AbilitySlice {
    public DataHelper dataHelper = DataHelper.getInstance();
    public Preferences sp = dataHelper.getSp(null);
    public PendingLiveData pending;

    @Override
    protected void onActive() {
        super.onActive();
        // 注册sp观察者
        pending = new PendingLiveData(this);
        sp.registerObserver(pending);
    }

    // 线程切换 + 绑定生命周期
    public <T> Observable<T> request(Observable<T> observable) {
        return observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(HmOSSchedulers.mainThread())
                // 模拟网络时延
                .delay(3, TimeUnit.SECONDS)
                .skipWhile(ipHttpBean -> this.getLifecycle().getLifecycleState() != Lifecycle.Event.ON_ACTIVE);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        sp.unregisterObserver(pending);
    }
}
